package com.topisv.tms.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.CustomerAreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.TaskNumber;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.entity.WarehouseTransfer;
import com.topisv.tms.entity.auth.TopisvOAuth;
import com.topisv.tms.platform.yhd.vo.YhdSessionKeyVo;
import com.topisv.tms.repository.AreaDao;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.CustomerAreaGroupDao;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.OrdenoSourceDao;
import com.topisv.tms.repository.RoleDao;
import com.topisv.tms.repository.ShopSourceDao;
import com.topisv.tms.repository.TaskNumberDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.UserroleDao;
import com.topisv.tms.repository.WarehouseTransferDao;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.utils.DigestsUtils;
import com.topisv.tms.utils.JobuuidUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.vo.warehouse.WarehouseAreaParamVo;
import com.topisv.tms.vo.warehouse.WarehouseAreaVo;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;
import com.yhd.object.store.StoreMerchantStoreInfo;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class CustomersService extends BaseService {

    private CustomersDao customersDao;
    @Autowired
    private TaskNumberDao taskNumberDao;
    @Autowired
    private OrdenoSourceDao ordenoSourceDao;
    @Autowired
    private ShopSourceDao shopSourceDao;
    @Autowired
    private AreaGroupDao areaGroupDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserroleDao userroleDao;
    @Autowired
    private CustomerAreaGroupDao customerAreaGroupDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private WarehouseTransferDao warehouseTransferDao;

    /**
     * 一号店商家注册
     * 
     * @param ysko
     * @param storeMerchantStoreInfo
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public User registerYhd(YhdSessionKeyVo ysko, StoreMerchantStoreInfo storeMerchantStoreInfo) throws Exception {
        ShopSource shopSource = null;
        User user = null;
        Customers customers = null;
        String customerCode = ysko.getMerchantId();
        try {
            // 1:新建用户,2:新建商家，3:新建店铺
            user = userDao.findByUserId(ysko.getUserId());
            if (user == null) {
                String jobuuid = JobuuidUtils.createJobuuid(ysko.getUserCode());
                // 1:新建用户
                Role role = roleDao.findByRolename("集发宝商家");
                if (role != null) {
                    user = new User();
                    user.setCreated(new Date());
                    user.setUsername(ysko.getUserCode());
                    user.setPlainPassword("123456");
                    user.setOpenPassword("123456");
                    user.setRealname(ysko.getNickName());
                    user.setUserType("customer");
                    user.setYhdUserType(ysko.getUserType());
                    user.setCustomerCode(customerCode);
                    user.setStatus("2");
                    user.setJobuuid(jobuuid);
                    user.setUserId(ysko.getUserId());
                    user.setSessionKey(ysko.getSessionKey());
                    user.setMerchantId(ysko.getMerchantId());
                    DigestsUtils.entryptPassword(user);
                    userDao.save(user);

                    Userrole userrole = new Userrole();
                    userrole.setUser(user);
                    userrole.setRole(roleDao.findOne(role.getId()));
                    userroleDao.save(userrole);

                }
                return user;
            }

            if ("2".equals(user.getStatus())) {// 未审核的用户
                return user;
            }

            // 2:新建商家
            customers = this.customersDao.findByCustomerCode(customerCode);
            if (customers == null) {
                OrdenoSource ordenoSource = this.ordenoSourceDao.findByOrdenoSourceCode("yhd");
                Integer startNum = Integer.parseInt(ordenoSource.getStartNum());
                customers = new Customers();
                customers.setCustomerName(ysko.getNickName());// 商家名称
                customers.setCustomerCode(customerCode);// 商家编码
                customers.setStartNumber((startNum + 1) + "");
                customers.setEndNumber("100000000");
                customers.setStartOrdeno((startNum + 1) + "100000000");
                customers.setPassBack("0");
                customers.setPlaceStatus("0");
                customers.setSectionPo("0");// 分仓宝商家
                customers.setStartPoint("0755");
                customers.setCustomerIntro("一号店卖家");
                customers.setAreasGroupInf("http://wms.paiu.com.cn/wms/api/ajaxAreaGroup");
                customers.setAreasUsername(ysko.getUserCode());
                customers.setAreasPassword("123");
                customers.setTmsBatchAddress("http://tms.paiu.com.cn/tms/api/v1/batch");
                customers.setTmsBatchAppkey(ysko.getUserCode());
                customers.setTmsBatchAppsecret("123456");
                customers.setSubStock("0");
                customers.setOrdenoSynchroInf("http://wms.paiu.com.cn/wms/soce/ordenoDetailed");
                ordenoSource.setStartNum((startNum + 1) + "");

                CustomerAreaGroup customersAreaGroup = new CustomerAreaGroup();
                customersAreaGroup.setCustomerCode(customerCode);
                customersAreaGroup.setAreaGroupCode("HD");

                customersAreaGroup.setUpdateDate(new Date());

                List<Area> areas = (List<Area>) this.areaDao.findAll();
                StringBuffer sb = new StringBuffer("");
                for (Area a : areas) {
                    if ("".equals(sb.toString())) {
                        sb.append(a.getAreaCode());
                    } else {
                        sb.append("," + a.getAreaCode());
                    }
                }
                customersAreaGroup.setAreaLists(sb.toString());
                this.customerAreaGroupDao.save(customersAreaGroup);
                customers.setCustomerAreaGroup(customersAreaGroup);
                try {
                    // 同步TMS商家信息
                    // ObjectMapper object=new ObjectMapper();
                    // String message=object.writeValueAsString(customers);
                    // SynchroShippedBatchQueue.putSendMessageQueue("createCustomers"+StatusEnums.split.getStatus()+message);

                } catch (Exception e) {

                }
                this.ordenoSourceDao.save(ordenoSource);
                this.save(customers, user.getJobuuid());
            }
            shopSource = shopSourceDao.findByYhdStoreId(storeMerchantStoreInfo.getStoreId() + "");
            // 新建店铺
            if (shopSource == null) {
                shopSource = new ShopSource();
                shopSource.setCreateDate(new Date());
                shopSource.setCustomerCode(customerCode);
                shopSource.setYhdAttitudeExactExpPoint(storeMerchantStoreInfo.getAttitudeExactExpPoint() + "");
                shopSource.setYhdDescriptExactExpPoint(storeMerchantStoreInfo.getDescriptExactExpPoint() + "");
                shopSource.setYhdLogisticeExactExpPoint(storeMerchantStoreInfo.getLogisticeExactExpPoint() + "");
                shopSource.setYhdStoreAddress(storeMerchantStoreInfo.getStoreAddress());
                shopSource.setYhdStoreCategoryCode(storeMerchantStoreInfo.getStoreCategoryCode() + "");
                shopSource.setYhdStoreId(storeMerchantStoreInfo.getStoreId() + "");
                shopSource.setYhdStoreMode(storeMerchantStoreInfo.getStoreMode());
                shopSource.setYhdStoreNickName(storeMerchantStoreInfo.getStoreNickName());
                shopSource.setYhdStoreOpenTime(storeMerchantStoreInfo.getStoreOpenTime());
                shopSource.setYhdStoreOperateCategory(storeMerchantStoreInfo.getStoreOperateCategory());
                shopSource.setShopCode(ysko.getUserCode() + "_" + storeMerchantStoreInfo.getStoreId());
                shopSource.setOrdenoSourceCode("yhd");
                shopSource.setShopName(storeMerchantStoreInfo.getStoreName());
                shopSource.setStatus("normal");
                this.shopSourceDao.save(shopSource);
            }
            if (user.getAreagroups() == null) {// 审核通过的用户增加网点信息
                List<AreaGroup> areaGroups = areaGroupDao.loadByCustomerCode(customerCode);
                user.setAreagroups(areaGroups.get(0).getGroupCode());
            }

            user.setSessionKey(ysko.getSessionKey());
            user.setMerchantId(ysko.getMerchantId());
            userDao.save(user);

            return user;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 根据客户编码返回平台
     * 
     * @param customerCode
     * @return
     */
    public List<OrdenoSource> findOrdenoSource(String customerCode) {
        List<OrdenoSource> ordenoSources = new ArrayList<OrdenoSource>();
        List<ShopSource> shopSources = shopSourceDao.findByCustomerCode(customerCode);
        Set<String> sb = new HashSet<String>();
        for (ShopSource shop : shopSources) {
            sb.add(shop.getOrdenoSourceCode());
        }
        for (String code : sb) {
            ordenoSources.add(ordenoSourceDao.findByOrdenoSourceCode(code));
        }
        return ordenoSources;
    }

    public Customers findOne(Long id) {
        return customersDao.findOne(id);
    }

    public Customers findByCustomerCode(String customerCode) {
        return customersDao.findByCustomerCode(customerCode);
    }

    public List<Customers> findByCustomers(String customerLists) {
        String[] customers = customerLists.split(":");
        List<Customers> lists = new ArrayList<Customers>();
        for (String c : customers) {
            if (!"paiu".equals(c)) {
                lists.add(customersDao.findByCustomerCode(c));
            }
        }
        return lists;
    }

    @Transactional(readOnly = false)
    public void save(Customers entity) throws Exception {
        try {
            customersDao.save(entity);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 增加商家的同时增加信息
     * 
     * @param entity
     * @param jobuuid
     * @throws Exception
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void save(Customers entity, String jobuuid) throws Exception {
        try {
            String batchNumber = "100,200,500,1000,1500,2000";
            String bachupNumber = "100,200,300,400,500";
            String mBachupNumber = "30,60,90";
            String[] types = { "single", "multiple", "forward" };
            Date nowDate = new Date();
            for (int i = 0; i < types.length; i++) {
                TaskNumber taskNumber = new TaskNumber();
                if ("multiple".equals(types[i])) {
                    taskNumber.setBackupTaskNumber(mBachupNumber);
                } else {
                    taskNumber.setBackupTaskNumber(bachupNumber);
                }

                taskNumber.setBatchTaskNumber(batchNumber);
                taskNumber.setCreateDate(nowDate);
                taskNumber.setCustomerCode(entity.getCustomerCode());
                taskNumber.setJobuuid(jobuuid);
                taskNumber.setType(types[i]);
                taskNumber.setUpdateDate(nowDate);
                taskNumberDao.save(taskNumber);
            }
            customersDao.save(entity);
            // 有以下角色的账户,自动新增用户权限
            // comment 20160606 只有admin角色的才自动绑定改商家 by lianghe.yuan, according to chenqiufeng
            // List<Userrole> roles =
            // userroleDao.findByRoleName(StatusEnums.user_type_paiu.getStatus(),
            // Arrays.asList("admin","仓库管理员","作业员","派友客服","退货管理"));
            List<Userrole> roles = userroleDao.findByRoleName(StatusEnums.user_type_paiu.getStatus(), Arrays.asList("admin"));
            Set<Long> users = new HashSet<Long>();
            for (Userrole userrole : roles) {
                User user = userrole.getUser();
                String customers = user.getCustomers();
                if (!users.contains(user.getId())) {
                    users.add(user.getId());
                    user.setCustomers(StringUtils.isBlank(customers) ? entity.getCustomerCode()
                            : new StringBuilder().append(customers).append(":").append(entity.getCustomerCode()).toString());
                }
            }
            // 创建仓库
            /** remove 20160606 by lianghe.yuan , according to yanlei **/
            /*AreaGroup group=new AreaGroup();
            group.setAreas(null);
            group.setCustomer(entity);
            group.setGroupCode(entity.getCustomerCode());
            group.setGroupName(entity.getCustomerName()+"仓库");
            group.setGroupIntro(entity.getCustomerName()+"仓库");
            group.setWarehouseType("customer");
            this.areaGroupDao.save(group);*/

        } catch (Exception e) {
            throw e;
        }
    }

    @Transactional(readOnly = false)
    public void delete(Long id) {
        customersDao.delete(id);
    }

    public List<Customers> findAll() {
        return (List<Customers>) customersDao.findAll();
    }

    public Page<Customers> pageCustomers(QueryParamHolder paramHolder) {
        return findByJson(paramHolder, customersDao, Customers.class);
    }

    @Autowired
    public void setCustomersDao(CustomersDao customersDao) {
        this.customersDao = customersDao;
    }

    /**
     * 根据用户权限查找商家
     * 
     * @param curUser
     * @return
     * @throws Exception
     */
    public List<Customers> loadCustomerByAuthority(ShiroUser curUser) {
        List<Customers> customerList = null;
        String userType = curUser.userType;
        if (StatusEnums.user_type_paiu.getStatus().equals(userType)) {// 派友用户
            customerList = this.findByCustomers(curUser.customers);
        } else if (StatusEnums.user_type_customer.getStatus().equals(userType)) {// 商家用户
            customerList = this.findByCustomers(curUser.customerCode);
        }
        return customerList;

    }

    /**
     * 根据用户权限查找商家
     * 
     * @param jobuuid
     * @return
     * @throws Exception
     */
    public String loadCustomerByAuthority(String jobuuid) {
        String customers = null;
        User user = this.userDao.findByJobuuid(jobuuid);
        String userType = user.getUserType();
        if (StatusEnums.user_type_paiu.getStatus().equals(userType)) {// 派友用户
            customers = user.getCustomers();
        } else if (StatusEnums.user_type_customer.getStatus().equals(userType)) {// 商家用户
            customers = user.getCustomerCode();
        }
        return customers;
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void save(Customers entity, ShopSource shopSource, User user, String jobuuid) throws Exception {
        try {
            this.save(entity, jobuuid);
            this.shopSourceDao.save(shopSource);
            this.userDao.save(user);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 淘宝商家注册
     * 
     * @param shopSource
     * @param t
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public User registerTaobao(ShopSource shopSource, TopisvOAuth t) throws Exception {
        User user = null;
        Customers customers = null;
        String customerCode = "";
        try {
            // 1:新建用户,2:新建商家，3:新建店铺
            user = userDao.findByUsername(shopSource.getTopisvNick());
            OrdenoSource ordenoSource = this.ordenoSourceDao.findByOrdenoSourceCode("tNormal");
            String cusCode = ordenoSource.getCusCode();
            int cusNum = ordenoSource.getCusNum();
            if (cusNum < 10) {
                customerCode = cusCode + "000" + cusNum;
            } else if (cusNum >= 10 && cusNum < 100) {
                customerCode = cusCode + "00" + cusNum;
            } else if (cusNum >= 100 && cusNum < 1000) {
                customerCode = cusCode + "0" + cusNum;
            } else if (cusNum >= 1000 && cusNum < 10000) {
                customerCode = cusCode + cusNum;
            }
            if (user == null) {
                String jobuuid = JobuuidUtils.createJobuuid(customerCode);
                // 1:新建用户
                Role role = roleDao.findByRolename("分仓宝商家");
                if (role != null) {

                    // 用户信息
                    user = new User();
                    user.setCreated(new Date());
                    user.setUsername(shopSource.getTopisvNick());
                    user.setPlainPassword("123456");
                    user.setOpenPassword("123456");
                    user.setRealname(shopSource.getTopisvNick());
                    user.setUserType("customer");
                    user.setCustomers(customerCode);
                    user.setCustomerCode(customerCode);
                    user.setStatus("1");
                    user.setJobuuid(jobuuid);
                    user.setUserId(shopSource.getTopisvUserId());
                    DigestsUtils.entryptPassword(user);

                    // 设置用户可访问的的仓库权限
                    user.setAreagroups(customerCode);

                    userDao.save(user);

                    // 角色
                    Userrole userrole = new Userrole();
                    userrole.setUser(user);
                    userrole.setRole(role);
                    userroleDao.save(userrole);
                }
            }

            // 2:新建商家,同时创建仓库
            customers = this.customersDao.findByCustomerCode(customerCode);
            if (customers == null) {
                Integer startNum = Integer.parseInt(ordenoSource.getStartNum());
                customers = new Customers();
                customers.setCustomerName(shopSource.getTopisvNick());// 商家名称
                customers.setCustomerCode(customerCode);// 商家编码
                customers.setStartNumber((startNum + 1) + "");
                customers.setEndNumber("100000000");
                customers.setStartOrdeno((startNum + 1) + "100000000");
                customers.setPassBack("0");
                customers.setPlaceStatus("0");
                customers.setSectionPo("0");// 分仓宝商家
                customers.setStartPoint("0755");
                customers.setCustomerIntro("淘宝卖家，自动创建");
                customers.setAreasGroupInf("http://wms.paiu.com.cn/wms/api/ajaxAreaGroup");
                customers.setAreasUsername(customerCode);
                customers.setAreasPassword("123");
                customers.setTmsBatchAddress("http://tms.paiu.com.cn/tms/api/v1/batch");
                customers.setTmsBatchAppkey(customerCode);
                customers.setTmsBatchAppsecret("123456");
                customers.setSubStock("0");
                customers.setOrdenoSynchroInf("http://wms.paiu.com.cn/wms/soce/ordenoDetailed");
                ordenoSource.setStartNum((startNum + 1) + "");
                ordenoSource.setCusNum(cusNum + 1);
                CustomerAreaGroup customersAreaGroup = new CustomerAreaGroup();
                customersAreaGroup.setCustomerCode(customerCode);
                customersAreaGroup.setAreaGroupCode("HN");

                customersAreaGroup.setUpdateDate(new Date());

                this.customerAreaGroupDao.save(customersAreaGroup);
                customers.setCustomerAreaGroup(customersAreaGroup);
                this.ordenoSourceDao.save(ordenoSource);
                this.save(customers, user.getJobuuid());
            }

            // 3.店铺
            shopSource.setCreateDate(new Date());
            shopSource.setCustomerCode(customerCode);
            shopSource.setShopCode(customerCode);
            shopSource.setOrdenoSourceCode("tNormal");
            shopSource.setStatus("normal");
            this.shopSourceDao.save(shopSource);

            return user;
        } catch (Exception e) {
            throw e;
        }
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void usingDistributeWarehouse(String customerCode, String type) {
        customersDao.updateDistributeWarehouseState(type, customerCode);
    }
    
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void updateStockQueryType(String customerCode, String type) {
        customersDao.updateStockQueryType(type, customerCode);
    }
    
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void bindWarehouse(String customerCode, String warehouseCode) {
        CustomerAreaGroup areaGroups = customerAreaGroupDao.findByCustomerCodeAndAreaGroupCode(customerCode, warehouseCode);
        if (areaGroups == null) {
            CustomerAreaGroup areaGroup = new CustomerAreaGroup();
            areaGroup.setCustomerCode(customerCode);
            areaGroup.setAreaGroupCode(warehouseCode);
            areaGroup.setUpdateDate(new Date());
            areaGroup.setCainiaoAddressStatus("0");
            customerAreaGroupDao.save(areaGroup);
        }
    }
    
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void bindPrimaryWarehouse(String warehouseCode , String customerCode){
        customersDao.updatePrimaryWarehouse(warehouseCode, customerCode);
    }
    
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void addWarehouseLevel(WarehouseAreaParamVo vo) {
        if (vo == null || vo.getWarehouseList() == null) {
            return;
        }
        // 删除商家下所有仓库记录
        warehouseTransferDao.deleteByCustomerCodeAndWarehouseCode(vo.getCustomerCode(), vo.getWarehouseCode());
        // 添加商家仓库对应的等级
        List<WarehouseTransfer> list =new ArrayList<WarehouseTransfer>();
        for (WarehouseAreaVo area : vo.getWarehouseList()) {
            if (StringUtils.isNotBlank(area.getLevel())) {
                WarehouseTransfer wTransfer = new WarehouseTransfer();
                wTransfer.setCustomerCode(vo.getCustomerCode());
                wTransfer.setWarehouseCode(vo.getWarehouseCode());
                wTransfer.setTransferWarehouseCode(area.getWarehouseCode());
                wTransfer.setLevel(Integer.valueOf(area.getLevel()));
                list.add(wTransfer);
            }
        }
        warehouseTransferDao.save(list);
    }

}
